package com.linlang.grasharepro.activity.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linlang.grasharepro.R;
import com.linlang.grasharepro.activity.CutPictureAty;
import com.linlang.grasharepro.activity.EditActivity;
import com.linlang.grasharepro.activity.MyCollectActivity;
import com.linlang.grasharepro.activity.MyFansActivity;
import com.linlang.grasharepro.activity.MyFollowActivity;
import com.linlang.grasharepro.activity.MyShareActivity;
import com.linlang.grasharepro.activity.PersonInfo;
import com.linlang.grasharepro.activity.ScoreActivity;
import com.linlang.grasharepro.dao.FansDB;
import com.linlang.grasharepro.dao.FollowDB;
import com.linlang.grasharepro.dao.ShareCoentenDB;
import com.linlang.grasharepro.dao.UserDB;
import com.linlang.grasharepro.model.Fans;
import com.linlang.grasharepro.model.Follow;
import com.linlang.grasharepro.model.ShareCoenten;
import com.linlang.grasharepro.model.User;
import com.linlang.grasharepro.utils.SelectDialog;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by lixin on 2016-8-6.
 */
public class MyCenterPage extends Fragment {

    private final int CAMERA_WITH_DATA = 1;
    /**
     * 本地图片选取标志
     */
    private static final int FLAG_CHOOSE_IMG = 2;
    /**
     * 截取结束标志
     */
    private static final int FLAG_MODIFY_FINISH = 3;
    public static final String TMP_PATH = "temp.jpg";

    private View view;
    private LinearLayout my, save, edit, collect;
    private TextView detail_user, detail_profe, detail_time, tv_introduction, slef_release, slef_love, slef_attention;
    private ImageView detail_type, detail_head;

    private ShareCoentenDB shareCoentenDB;
    private FansDB fansDB;
    private FollowDB followDB;
    private UserDB userDB;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.mycenterpage, container, false);
        initView();
        initData();
        return view;
    }

    private void initView() {
        my = (LinearLayout) view.findViewById(R.id.mine_my);
        save = (LinearLayout) view.findViewById(R.id.mine_save);
        edit = (LinearLayout) view.findViewById(R.id.mine_edit);
        collect = (LinearLayout) view.findViewById(R.id.mine_collect);
        detail_head = (ImageView) view.findViewById(R.id.detail_head);
        slef_release = (TextView) view.findViewById(R.id.slef_release);//我发布的
        slef_love = (TextView) view.findViewById(R.id.slef_love);//我的粉丝
        slef_attention = (TextView) view.findViewById(R.id.slef_attention);//我的关注
        my.setOnClickListener(new MyOnClickListener(0));
        save.setOnClickListener(new MyOnClickListener(1));
        edit.setOnClickListener(new MyOnClickListener(2));
        collect.setOnClickListener(new MyOnClickListener(3));

        slef_release.setOnClickListener(new MyOnClickListener(4));
        slef_love.setOnClickListener(new MyOnClickListener(5));
        slef_attention.setOnClickListener(new MyOnClickListener(6));
        detail_head.setOnClickListener(new MyOnClickListener(7));
    }

    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        Intent intent = null;

        @Override
        public void onClick(View v) {
            switch (index) {
                case 0:
                    intent = new Intent(getActivity(),
                            PersonInfo.class);
                    break;
                case 1:
                    intent = new Intent(getActivity(),
                            ScoreActivity.class);
                    break;
                case 2:
                    intent = new Intent(getActivity(),
                            EditActivity.class);
                    break;
                case 3:
                    intent = new Intent(getActivity(),
                            MyCollectActivity.class);
                    break;
                case 4:
                    intent = new Intent(getActivity(),
                            MyShareActivity.class);
                    break;
                case 5:
                    intent = new Intent(getActivity(),
                            MyFansActivity.class);
                    break;
                case 6:
                    intent = new Intent(getActivity(),
                            MyFollowActivity.class);
                    break;
                case 7:
                    showSelectPictureMenu();
                    break;
            }
            if (index != 7)
                startActivity(intent);
        }
    }

    public void initData() {
        detail_user = (TextView) view.findViewById(R.id.detail_user);
        detail_profe = (TextView) view.findViewById(R.id.detail_profe);
        detail_time = (TextView) view.findViewById(R.id.detail_time);
        detail_type = (ImageView) view.findViewById(R.id.detail_type);
        tv_introduction = (TextView) view.findViewById(R.id.tv_introduction);
        detail_head = (ImageView) view.findViewById(R.id.detail_head);

        //获取用户登陆信息
        SharedPreferences preferences = getActivity().getSharedPreferences("userInfo",
                Activity.MODE_PRIVATE);
        String account = preferences.getString("account", "");
        String type = preferences.getString("type", "");
        String major = preferences.getString("major", "");
        String academicStarts = preferences.getString("academicStarts", "");
        String introduction = preferences.getString("introduction", "");
        String headUrl = preferences.getString("headUrl","");

        detail_user.setText(account);
        detail_profe.setText(major);
        detail_time.setText(academicStarts);
        tv_introduction.setText(introduction);

        Bitmap b = BitmapFactory.decodeFile(headUrl);
        detail_head.setImageBitmap(b);

        if (type.equals("在校生"))
            detail_type.setImageResource(R.drawable.inschool);
        else
            detail_type.setImageResource(R.drawable.outschool);


        shareCoentenDB = new ShareCoentenDB(getContext());
        shareCoentenDB.open();
        ArrayList<ShareCoenten> shareCoentens = shareCoentenDB.queryByWhere(account);

        fansDB = new FansDB(getContext());
        fansDB.open();
        ArrayList<Fans> fanses = fansDB.getMyFans(account);

        followDB = new FollowDB(getContext());
        followDB.open();
        ArrayList<Follow> follows = followDB.getMyFollow(account);

        slef_release.setText("发布(" + shareCoentens.size() + ")");
        slef_love.setText("粉丝(" + fanses.size() + ")");
        slef_attention.setText("关注(" + follows.size() + ")");
    }

    /**
     * 弹出选择照片菜单
     */
    public void showSelectPictureMenu() {
        new SelectDialog(getContext())
                .builder()
                .setCancelable(true)
                .setTitle("请选择操作")
                .setCanceledOnTouchOutside(true)
                .addSelectItem("相机", SelectDialog.SelectItemColor.Green,
                        new SelectDialog.OnSelectItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                startCamera();
                            }
                        })
                .addSelectItem("图库", SelectDialog.SelectItemColor.Green,
                        new SelectDialog.OnSelectItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                startAlbum();
                            }
                        }).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == getActivity().RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    Cursor cursor = getActivity().getContentResolver().query(uri,
                            new String[]{MediaStore.Images.Media.DATA},
                            null, null, null);
                    if (null == cursor) {
                        Toast.makeText(getActivity().getApplicationContext(), "图片没找到", Toast.LENGTH_LONG)
                                .show();
                        return;
                    }
                    cursor.moveToFirst();
                    String path = cursor.getString(cursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    cursor.close();

                    //修改用户头像
                    updateUserHead(path);

                    Intent intent = new Intent(getActivity(), CutPictureAty.class);
                    intent.putExtra("path", path);
                    startActivityForResult(intent, FLAG_MODIFY_FINISH);
                } else {
                    //修改用户头像
                    updateUserHead(uri.getPath());

                    Intent intent = new Intent(getActivity(), CutPictureAty.class);
                    intent.putExtra("path", uri.getPath());
                    startActivityForResult(intent, FLAG_MODIFY_FINISH);
                }
            }
        } else if (requestCode == FLAG_MODIFY_FINISH && resultCode == getActivity().RESULT_OK) {
            if (data != null) {
                String path = data.getStringExtra("path");
                Bitmap b = BitmapFactory.decodeFile(path);
                detail_head.setImageBitmap(b);

                //修改用户头像
                updateUserHead(path);
            }
        }
        switch (requestCode) {
            case CAMERA_WITH_DATA:
                // 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                startCropImageActivity(Environment.getExternalStorageDirectory()
                        + "/" + TMP_PATH);
                break;
        }
    }

    //
    public void updateUserHead(String path){

        //获取用户登陆信息
        SharedPreferences preferences = getActivity().getSharedPreferences("userInfo",
                Activity.MODE_PRIVATE);
        String id = preferences.getString("id", "");
        String account = preferences.getString("account", "");

        User user = new User();
        user.set_Id(id);
        user.setHeadUrl(path);
        userDB = new UserDB(getContext());
        userDB.open();
        userDB.updateUserHead(user);

        ShareCoentenDB shareCoentenDB = new ShareCoentenDB(getContext());
        shareCoentenDB.open();

        ShareCoenten shareCoenten = new ShareCoenten();
        shareCoenten.setUserName(account);
        shareCoenten.setHeadUrl(path);
        shareCoentenDB.updateHead(shareCoenten);
    }
    // 裁剪图片的Activity
    private void startCropImageActivity(String path) {
        Intent intent = new Intent(getActivity(), CutPictureAty.class);
        intent.putExtra("path", path);
        startActivityForResult(intent, FLAG_MODIFY_FINISH);
    }

    private void startAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, FLAG_CHOOSE_IMG);
    }

    private void startCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                Environment.getExternalStorageDirectory(), TMP_PATH)));
        startActivityForResult(intent, CAMERA_WITH_DATA);
    }
}
